import React, { memo } from "react";
import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import MyTarbar from "../component/MyTarbar";
import MyNavbar from "../component/MyNavbar";
import { useDispatch, useSelector } from "react-redux";
import { ProductCard, Button, Notify } from "react-vant";
import { addOne } from "../dea/shop";
const Home = memo(() => {
  let location = useLocation();
  let token = localStorage.getItem("token");
  let navigate = useNavigate();
  let list = useSelector((state) => state.shop.list);
  let dispatch = useDispatch();
  // 路由守卫
  useEffect(() => {
    // 如果浏览器识别不到token码并且你跳转的路由地址不是登录
    if (!token && location.pathname !== "/login") {
      // 强制跳转到登录页
      navigate("/login");
    }
  }, [location]);
  // 点击加购
  const add = (id) => {
    Notify.show({ type: "success", message: "加入购物车成功，快去查看吧~" });
    dispatch(addOne(id));
  };
  return (
    <div>
      <div>
        <MyNavbar></MyNavbar>
      </div>
      <div>
        {list.map((item, index) => {
          return (
            <ProductCard
              key={item.id}
              price={item.price}
              title={item.title}
              thumb="https://img.yzcdn.cn/vant/ipad.jpeg"
              footer={
                <>
                  <Button
                    size="mini"
                    round
                    plain
                    style={{ marginRight: 2 }}
                    onClick={() => add(item.id)}
                  >
                    点击加购
                  </Button>
                </>
              }
            />
          );
        })}
      </div>
      <div>
        <MyTarbar></MyTarbar>
      </div>
    </div>
  );
});

export default Home;
